package com.yzdbx.task;

import cn.hutool.core.util.RandomUtil;
import com.yzdbx.utils.GenUtil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.yzdbx.utils.DbUtil.getMaxId;

/**
 * @BelongsProject: SERVEVICE-DATA-GEN
 * @BelongsPackage: com.yzdbx.task
 * @Author: lk
 * @CreateTime: 2025-05-14
 * @Description: TODO
 * @Version: 1.0
 */
@SuppressWarnings("all")
public class PurchaseRunnable implements Exe {


    private Connection connection;

    private static final String ALL_SUPPLIER_SQL = "select id from  supplyManagement";
     private static final String ALL_PRODUCT_SQL = "select id from gy02ProductRepository where productClassification in ('主材','辅材')";
//    private static final String ALL_PRODUCT_SQL = "select id from gy02ProductRepository where productClassification in ('原材料')";
    private static final String ALL_USER_SQL = "select memberId as ID from corp_member where memberId != 'admin123'";
    public static final ThreadLocal<List<Integer>> GEN_PURCHASE_IDS = new ThreadLocal<>();

    public PurchaseRunnable(Connection connection) {
        this.connection = connection;
    }

    public boolean execute(int count) {
        List<Integer> genPurchaseIds = new ArrayList<>();
        try {
            //查询客户信息
            PreparedStatement statement = connection.prepareStatement(ALL_SUPPLIER_SQL);
            ResultSet resultSet = statement.executeQuery();
            List<Integer> clientIds = new ArrayList<>();

            while (resultSet.next())
                clientIds.add(resultSet.getInt("ID"));

            // 校验供应商列表非空
            if (clientIds == null || clientIds.isEmpty()) {
                throw new RuntimeException("供应商列表为空，无法生成采购单！");
            }

            //查询产品库
            List<Integer> productIds = new ArrayList<>();
            statement = connection.prepareStatement(ALL_PRODUCT_SQL);
            resultSet = statement.executeQuery();
            while (resultSet.next())
                productIds.add(resultSet.getInt("ID"));

            // 校验产品库非空
            if (productIds == null || productIds.isEmpty()) {
                throw new RuntimeException("产品库为空，无法生成采购明细！");
            }

            //查询用户
            List<String> userIds = new ArrayList<>();
            statement = connection.prepareStatement(ALL_USER_SQL);
            resultSet = statement.executeQuery();
            while (resultSet.next())
                userIds.add(resultSet.getString("ID"));

            // 校验用户列表非空
            if (userIds == null || userIds.isEmpty()) {
                throw new RuntimeException("用户列表为空，无法分配采购人员！");
            }


            int maxOrderId = getMaxId(connection, "cgPurchaseOrderForms");


            for (int i = 1; i <= count; i++) {

                int orderCount = 0;
                BigDecimal totalPrice = BigDecimal.ZERO;

                int curOrderId = maxOrderId + i;
                genPurchaseIds.add(curOrderId);
                //生成若干条订单明细
                int detailCount = RandomUtil.randomInt(1, 4);

                int detailMaxId = getMaxId(connection, "breakdownOfPurchaseOrders");
                for (int j = 1; j <= detailCount; j++) {
                    List<Integer> proIds = new ArrayList<>();
                    statement = connection.prepareStatement("insert into breakdownOfPurchaseOrders (id,procurementInformation,procurementVolume,unitPrice,numberOfShipmentsArrived,numberOfRefunds,associatedPurchaseOrders,f739,f12e) values (" +
                            "?,?,?,?,?,?,?,?,?" +
                            ")");

                    statement.setInt(1, detailMaxId + j);
                    statement.setInt(2, GenUtil.getNoRepeatId(RandomUtil.randomEle(productIds), proIds, productIds));
                    int number = RandomUtil.randomInt(1, 3000);
                    statement.setInt(3, number);
                    BigDecimal unitPrice = RandomUtil.randomBigDecimal(BigDecimal.ONE, BigDecimal.valueOf(20)).setScale(2, BigDecimal.ROUND_HALF_UP);
                    statement.setBigDecimal(4, unitPrice);
                    statement.setInt(5,number);
                    statement.setInt(6, 0);
                    statement.setInt(7, curOrderId);
                    statement.setTimestamp(8,GenUtil.CUR_TIME_STAMP.get());
                    statement.setString(9, RandomUtil.randomEle(userIds));
                    orderCount += number;
                    totalPrice = totalPrice.add(unitPrice.multiply(BigDecimal.valueOf(number)));
                    statement.execute();

             }
                statement = connection.prepareStatement("insert into cgPurchaseOrderForms (id,purchaseOrderNumber,chiefProcurementOfficer,dateOfProcurement,associatedSuppliers,auditStatus,procurementVolume,amountProcured,numberOfShipmentsArrived,amountOfGoodsToBeDelivered,synchronisingFolderFailedSS,created) values (" +
                        "?,?,?,?,?,?,?,?,?,?,?,?)");

                statement.setInt(1, curOrderId);
                statement.setString(2, GenUtil.getNoFromTable(connection, "CGDD", "cgPurchaseOrderForms", "purchaseOrderNumber"));
                statement.setString(3, RandomUtil.randomEle(userIds));
                statement.setDate(4, Date.valueOf(GenUtil.CUR_DATE.get()));
                statement.setInt(5, RandomUtil.randomEle(clientIds));
                statement.setString(6, "已通过");
                statement.setInt(7, orderCount);
                statement.setBigDecimal(8, totalPrice);

                statement.setInt(9, orderCount);
                statement.setBigDecimal(10, totalPrice);
                statement.setString(11,RandomUtil.randomEle(userIds));
                statement.setTimestamp(12, GenUtil.CUR_TIME_STAMP.get());

                statement.execute();
            }

        } catch (Exception e) {

           throw new RuntimeException("数据生成失败",e);
        }

        GEN_PURCHASE_IDS.set(genPurchaseIds);

        return Boolean.TRUE;
    }


}
